package cn.com.nes.site.service.project.handler;

import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.mybatis.agent.project.entity.TProject;
import cn.com.nes.mybatis.agent.system.entity.TUser;
import cn.com.nes.site.service.project.bo.QueryInstallWorkAreaBO;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 使用项目uuid的行政区划处理器
 */
@Component("workAreaHandlerUseProjectUuid")
public class WorkAreaHandlerUseProjectUuid extends WorkAreaHandler {

    @Override
    public Set<String> queryInstallWorkArea(QueryInstallWorkAreaBO queryBO) throws Exception {
        Set<String> areaCodeSet = super.queryInstallWorkArea(queryBO);

        // 获取关联的所有项目的行政区划集合
        for (String projectUuid : queryBO.getProjectUuidSet()) {
            TProject project = tProjectService.getProject(projectUuid);
            TUser user = systemUserService.getUser(project.getCompanyId(), queryBO.getEasyRepairUserId());

            List<String> serviceUserAllAreaCodes = projectServiceUserAuthService.getServiceUserAllAreaCodes(user.getId(), projectUuid);
            if (CollUtil.isEmpty(serviceUserAllAreaCodes)) {
                continue;
            }

            // 收集符合条件的行政区划代码
            if (StrUtil.isNotBlank(queryBO.getAreaCode())) {
                areaCodeSet.addAll(serviceUserAllAreaCodes.stream()
                        .filter(n -> n.startsWith(XzqhUtils.getRegionCodePrefix(queryBO.getAreaCode())) && !n.equals(queryBO.getAreaCode()))
                        .collect(Collectors.toSet()));
            } else {
                areaCodeSet.addAll(serviceUserAllAreaCodes);
            }
        }

        // 判断是否继续向后执行
        if (ObjectUtil.isNotNull(this.getSuccessor())) {
            queryBO.setAreaCodeSet(areaCodeSet);
            return this.getSuccessor().queryInstallWorkArea(queryBO);
        }
        return areaCodeSet;
    }
}
